<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/11/17
 * Time: 9:02 AM
 */
declare(strict_types=1);


namespace application\module\admin\controller;


use wshore\core\Dao;
use wshore\core\Response;
use wshore\core\Storage;

class database extends admin
{

    private $backupPath = WS_PATH_DATA . 'backup/';


    public function __construct()
    {
        parent::__construct();
        is_dir($this->backupPath) or mkdir($this->backupPath, 0777, true);
    }

    /**
     * 数据库备份/还原列表
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index()
    {
        //渲染模板
        $this->doLayoutAssign();
        $this->display();
    }

    /**
     * 获取数据库结构
     * @return void
     */
    public function getStruct()
    {
        $_list = Dao::getInstance()->query('SHOW TABLE STATUS');
        $list = [];
        foreach ($_list as $item) {
            if ($item['Comment'] !== 'VIEW') {
                $list[] = $item;
            }
        }
        Response::success('OK', $list);
    }


    /**
     * 优化表
     * @param  String $tables 表名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function optimize($tables = null)
    {
        $tables = rtrim($tables, ',');
        if ($tables) {
            if (strpos($tables, ',')) {
                # 加上 ``
                $tables = explode(',', $tables);
                $tables = implode('`,`', $tables);
            }
            $res = Dao::getInstance()->query("OPTIMIZE TABLE `{$tables}`");
            if ($res) {
                Response::success("数据表'{$tables}'优化完成！");
            } else {
                Response::failure("数据表'{$tables}'优化出错请重试！");
            }
        } else {
            Response::failure("请指定要优化的表！");
        }
    }

    public function listBackup(string $table)
    {
        $dir = $this->backupPath . $table;
        $_list = Storage::readdir($dir);
        $list = [];
        foreach ($_list as $filename => $item) {
            $filename = trim($filename, ' \\/');
            $time = intval(substr($filename, 0, strpos($filename, '.')));
            $list[] = $time;
        }
        Response::success('OK', $list);
    }

    /**
     * @deprecated
     * @param string $table
     * @param int $timestamp
     * @return void
     */
    public function restore(string $table, int $timestamp)
    {
        Response::failure('待完成...');
    }

    /**
     * 备份数据表
     * TODO:多个表分批次备份
     * @author linzh
     * @param string $tables
     */
    public function backup(string $tables)
    {
        set_time_limit(180);
        ini_set('memory_limit', '1024M');
        if ($tables = rtrim($tables, ',')) {
            if (strpos($tables, ',')) {
                # 加上 ``
                $tables = explode(',', $tables);
            } else {
                $tables = [$tables];
            }
            $count = 0;
            foreach ($tables as $table) {
                if (!Dao::getInstance()->backup($table)) {
                    Response::failure("数据表'{$table}'备份出错！");
                }
                $count++;
            }
            Response::success("成功备份'{$count}'个表！");
        } else {
            Response::failure("请指定要备份的表！");
        }
    }

    /**
     * 修复表
     * @param  String $tables 表名
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function repair(string $tables)
    {
        $tables = rtrim($tables, ',');
        if ($tables) {
            if (strpos($tables, ',')) {
                # 加上 ``
                $tables = explode(',', $tables);
                $tables = implode('`,`', $tables);
            }
            $res = Dao::getInstance()->query("REPAIR TABLE `{$tables}`");
            if ($res) {
                Response::success("数据表'{$tables}'修复完成！");
            } else {
                Response::failure("数据表'{$tables}'修复出错请重试！");
            }
        } else {
            Response::failure("请指定要修复的表！");
        }
    }

    /**
     * 删除备份文件
     * @param  Integer $time 备份时间
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function del($time = 0)
    {
        if ($time) {
            $name = date('Ymd-His', $time) . '-*.sql*';
            $path = realpath($this->backupPath) . DIRECTORY_SEPARATOR . $name;
            array_map("unlink", glob($path));
            if (count(glob($path))) {
                Response::failure('备份文件删除失败，请检查权限！');
            } else {
                Response::success('备份文件删除成功！');
            }
        } else {
            Response::failure('参数错误！');
        }
    }


}